<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="小说标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入小说标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生成状态" prop="generateStatus">
        <el-select v-model="queryParams.generateStatus" placeholder="请选择生成状态" clearable>
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['novel:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['novel:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['novel:project:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="projectList"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="小说标题" align="center" prop="title" />
      <el-table-column label="封面图" align="center" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.coverImageUrl"
            :src="scope.row.coverImageUrl"
            :preview-src-list="[scope.row.coverImageUrl]"
            fit="cover"
            class="cover-image"
          />
          <el-icon v-else><Picture /></el-icon>
        </template>
      </el-table-column>
      <el-table-column label="生成状态" align="center" prop="generateStatus" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.generateStatus)">
            {{ getStatusText(scope.row.generateStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="当前步骤" align="center" prop="currentStep" width="120">
        <template #default="scope">
          <el-tag :type="getStepType(scope.row.currentStep)">
            {{ getStepText(scope.row.currentStep) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click.stop="handleUpdate(scope.row)"
            v-hasPermi="['novel:project:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click.stop="handleDelete(scope.row)"
            v-hasPermi="['novel:project:remove']"
          >删除</el-button>
          <el-button
            link
            type="success"
            icon="Right"
            @click.stop="handleNextStep(scope.row)"
            v-if="scope.row.generateStatus !== 2"
          >继续创作</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="projectFormRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="小说标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入小说标题" />
        </el-form-item>
        <el-form-item label="小说简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入小说简介"
          />
        </el-form-item>
        <el-form-item label="生成状态" prop="generateStatus">
          <el-select v-model="form.generateStatus" placeholder="请选择生成状态">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前步骤" prop="currentStep">
          <el-select v-model="form.currentStep" placeholder="请选择当前步骤">
            <el-option label="世界观设定" :value="1" />
            <el-option label="角色设定" :value="2" />
            <el-option label="主线剧情" :value="3" />
            <el-option label="分卷规划" :value="4" />
            <el-option label="章节大纲" :value="5" />
            <el-option label="章节写作" :value="6" />
            <el-option label="完成" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.coverImageUrl" :src="form.coverImageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import { listProject, getProject, addProject, updateProject, delProject } from '@/api/novel/project'
import { parseTime } from '@/utils/ruoyi'
import { getToken } from '@/utils/auth'

const router = useRouter()

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  generateStatus: undefined
})

// 表单参数
const form = ref({
  id: undefined,
  title: '',
  description: '',
  coverImageUrl: '',
  generateStatus: 0,
  currentStep: 1
})

// 表单校验规则
const rules = ref({
  title: [
    { required: true, message: "小说标题不能为空", trigger: "blur" }
  ],
  description: [
    { required: true, message: "小说简介不能为空", trigger: "blur" }
  ]
})

// 项目列表数据
const projectList = ref([])

// 上传相关
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/common/upload"
const headers = { Authorization: "Bearer " + getToken() }

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',
    1: 'warning',
    2: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已完成'
  }
  return statusMap[status] || '未知'
}

// 获取步骤类型
const getStepType = (step) => {
  const stepMap = {
    1: 'info',
    2: 'warning',
    3: 'warning',
    4: 'warning',
    5: 'warning',
    6: 'warning',
    7: 'success'
  }
  return stepMap[step] || 'info'
}

// 获取步骤文本
const getStepText = (step) => {
  const stepMap = {
    1: '世界观设定',
    2: '角色设定',
    3: '主线剧情',
    4: '分卷规划',
    5: '章节大纲',
    6: '章节写作',
    7: '完成'
  }
  return stepMap[step] || '未知'
}

// 获取项目列表
const getList = async () => {
  loading.value = true
  try {
    const response = await listProject(queryParams)
    projectList.value = response.rows
    total.value = response.total
  } catch (error) {
    console.error('获取项目列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.title = undefined
  queryParams.generateStatus = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = "添加小说项目"
}

// 修改按钮操作
const handleUpdate = async (row) => {
  loading.value = true
  try {
    const response = await getProject(row.id || ids.value[0])
    form.value = response.data
    open.value = true
    title.value = "修改小说项目"
  } catch (error) {
    console.error('获取项目详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除按钮操作
const handleDelete = async (row) => {
  const projectIds = row.id || ids.value
  try {
    await ElMessageBox.confirm('是否确认删除小说项目编号为"' + projectIds + '"的数据项？', '警告', {
      type: 'warning'
    })
    loading.value = true
    await delProject(projectIds)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    console.error('删除失败:', error)
  } finally {
    loading.value = false
  }
}

// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    title: '',
    description: '',
    coverImageUrl: '',
    generateStatus: 0,
    currentStep: 1
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 提交按钮
const submitForm = async () => {
  try {
    if (form.value.id) {
      await updateProject(form.value)
      ElMessage.success('修改成功')
    } else {
      await addProject(form.value)
      ElMessage.success('新增成功')
    }
    open.value = false
    getList()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  form.value.coverImageUrl = response.url
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传文件只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理行点击
const handleRowClick = (row) => {
  // 可以在这里处理行点击事件，比如查看详情等
}

// 处理下一步
const handleNextStep = (row) => {
  // 根据当前步骤跳转到对应的页面
  const stepRoutes = {
    1: '/novel/worldSetting',
    2: '/novel/character',
    3: '/novel/mainPlot',
    4: '/novel/volume',
    5: '/novel/chapterOutline',
    6: '/novel/chapterContent'
  }

  const nextRoute = stepRoutes[row.currentStep]
  if (nextRoute) {
    router.push({
      path: nextRoute,
      query: { projectId: row.id }
    })
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.mb8 {
  margin-bottom: 8px;
}

.cover-image {
  width: 60px;
  height: 80px;
  border-radius: 4px;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;

  &:hover {
    border-color: var(--el-color-primary);
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>
